﻿/*
 * Created by SharpDevelop.
 * User: Matjaz
 * Date: 5.11.2007
 * Time: 22:41
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;

using Microsoft.Win32;

namespace gopher
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		string crlf = "\r\n";
		//table of items
		public List<int> indexList = new List<int>();
		public List<string> infoList = new List<string>();
		public List<string> descList = new List<string>();
		public List<string> selectList = new List<string>();
		public List<string> addressList = new List<string>();
		public List<string> portList = new List<string>();
		public List<string> plusList = new List<string>();
		//plus support
		public List<string> ABSTRACTList = new List<string>();
		public List<string> ADMINList = new List<string>();
		public List<string> VIEWList = new List<string>();
		public List<string> INTEGRITYList = new List<string>();
		public List<string> ASKList = new List<string>();
		//search
		public string searchString = "";
		//socket timeout
		public int waitTimeout = 500;
		//history
		public List<int> indexHist = new List<int>();
		public List<string> descHist = new List<string>();
		public List<string> selectHist = new List<string>();
		public List<string> addressHist = new List<string>();
		public List<string> portHist = new List<string>();
		//printing
		private PrintDocument printDoc = new PrintDocument();
		public StringBuilder printSB = new StringBuilder();
		private printersupport _printdocument = new printersupport();
		//settings
		private string homeServer = "";
		private string homeSelector = "";
		private string homePort = "";
		private string downloadsFolder = "";
		private string searchServer = "";
		private string searchSelector = "";
		private string searchPort = "";
		private string plusOn = "";
		private string plusRefreshOn = "";
		private int plusFileSizeWarning = 0;
		//favourites
		private string favouritesFile;
		private string settingsFile;
		private string settingsDir;
		//plus info
		private List<string> plusViews = new List<string>();
		private List<string> plusAsk = new List<string>();
		private List<string> plusLanguages = new List<string>();
		private List<string> plusFileSizes = new List<string>();
		private List<string> rtfData = new List<string>();
		private List<string> rtfLinks = new List<string>();
		private List<string> rtfSelectors = new List<string>();
		private string plusAbstract = "";
		private string plusAdmin = "";
		private string plusModified = "";
		private string plusIntegrity = "";
		private bool doAsk = false;
		public List<string> askMenu = new List<string>();
		//vsebina dveh datotek z nastavitvami
		private List<string> listOfLanguages = new List<string>();
		private List<string> listOfViews = new List<string>();
		//argumenti ob zagonu
		private string[] arguments;
		
		public MainForm(string[] args)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			arguments = args;
		}
		
		#region not_used
		static string ReadLine2 (Stream s)
		{
			List<byte> lineBuffer = new List<byte>();
			while (true)
			{
				int b = s.ReadByte();
				if (b == 10 || b < 0) break;
				if (b != 13) lineBuffer.Add ((byte)b);
			}
			return Encoding.UTF8.GetString (lineBuffer.ToArray());
			//return Encoding.ASCII.GetString (lineBuffer.ToArray());
		}
		#endregion
		
		string ReadLine (ref Socket server)
		{
			List<byte> lineBuffer = new List<byte>();
			//--------------------------------------------------------------
			byte[] data = new byte[1];
			server.ReceiveTimeout = 30000;//timeout
			int recv = server.Receive(data);
			lineBuffer.AddRange(data);

			while(true)
			{
				recv = server.Receive(data);
				lineBuffer.AddRange(data);
				if(recv == 0)
				{
					lineBuffer.AddRange(data);
					break;
				}
			}
			//--------------------------------------------------------------
			return Encoding.UTF8.GetString (lineBuffer.ToArray());
		}
		
		static void SendCommand (ref Socket server, string line)
		{
			try
			{
				server.Send(Encoding.ASCII.GetBytes(line+"\r\n"));
			}
			catch (Exception e)
			{
				MessageBox.Show("Error sending data to the network."+Environment.NewLine+Environment.NewLine+e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		
		#region not_used
		static void SendCommand2 (Stream stream, string line)
		{
			try
			{
				//Encoding myEncoding = Encoding.ASCII;
				//byte[] data = myEncoding.GetBytes(line + "\r\n");
				byte[] data = Encoding.UTF8.GetBytes (line + "\r\n");
				//byte[] data = Encoding.ASCII.GetBytes (line + "\r\n");
				stream.Write (data, 0, data.Length);
			}
			catch (Exception e)
			{
				MessageBox.Show("Error sending data to the network."+Environment.NewLine+Environment.NewLine+e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		#endregion
		
		/// <summary>
		/// Cleans all the lists (history, list of items, list of + items ...
		/// </summary>
		void Cleanup()
		{
//			for (int i = gopherMenu.Items.Count; i > 0; i--)
//			{
//				gopherMenu.Items.RemoveAt(0);
//			}
			gopherMenu.Items.Clear();
			indexList.Clear();
			infoList.Clear();
			descList.Clear();
			selectList.Clear();
			addressList.Clear();
			portList.Clear();
			plusList.Clear();
			printSB.Remove(0, printSB.Length);
			
			ADMINList.Clear();
			VIEWList.Clear();
			ASKList.Clear();
			ABSTRACTList.Clear();
			//LANGUAGEList.Clear();
			
			richTextBox.Rtf = "";
			rtfData.Clear();
			rtfLinks.Clear();
			rtfSelectors.Clear();
			splitContainerContent.Panel2Collapsed = true;
		}
		
		void CleanHistory()
		{
			for (int i = historyButton.DropDownItems.Count; i > 0; i--)
			{
				historyButton.DropDownItems.RemoveAt(0);
			}
//			indexHist.Clear();
//			descHist.Clear();
//			selectHist.Clear();
//			addressHist.Clear();
//			portHist.Clear();
		}
		
		void clearButtonClick(object sender, EventArgs e)
		{
			Cleanup();
		}
		
		void ExitToolStripMenuItemClick(object sender, EventArgs e)
		{
			this.Close();
		}
		
		void getDirectory(string selektor, string streznik, string vrata/*, Int32 timeout*/)
		{
			this.Cursor = Cursors.WaitCursor;
			int iPort=70;
			Cleanup();
			try
			{
				iPort = Convert.ToInt32(vrata);
			}
			catch (Exception ex)
			{
				MessageBox.Show("It seems that the 'port' number is wrong - it is not a number or it is out of range 0-65535"+Environment.NewLine+Environment.NewLine+ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				this.Cursor = Cursors.Default;
			}
			
			IPHostEntry objIPHostEntry;
			
			try
			{
				objIPHostEntry = Dns.GetHostEntry(streznik);
				IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(objIPHostEntry.AddressList[0].ToString()), iPort);

				Socket server = new Socket(AddressFamily.InterNetwork,
				                           SocketType.Stream, ProtocolType.Tcp);

				server.Connect(ipep);
//			}
//			catch (SocketException e)
//			{
//				MessageBox.Show("Unable to connect to server.\n"+e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//				this.Cursor = Cursors.Default;
//				return;
//			}
//			try
//			{
				SendCommand(ref server, selektor);
				List<string> imenik = new List<string>();
				string menu = ReadLine(ref server);
				//server.Shutdown(SocketShutdown.Both);
				server.Close();
				
				menu = menu.Replace("\0", string.Empty);
				
				foreach(string vrstica in menu.Split((crlf).ToCharArray()))
				{
					string temps = vrstica;
					//temps = temps.Replace("\0", string.Empty);
					if(temps == ".") break;
					if(temps.TrimEnd() == string.Empty) {}
					if(temps != string.Empty) imenik.Add(temps);
				}
				//MessageBox.Show(menu);
//				StreamWriter sw = new StreamWriter("mm.txt");
//				sw.Write(menu);
//				sw.Flush();
//				sw.Close();
				writeDirectory(imenik);
				DodajStatus(selektor, streznik, vrata);
				this.Cursor = Cursors.Default;
			}
			catch(Exception ex)
			{
				this.Cursor = Cursors.Default;
				MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		
		void writeDirectory(List<string> imenik)
		{
			try
			{
				int i = 0;
				//rtfData.Clear();
				i = 0;
				bool plus = false;
				bool View = false;
				bool Abstract = false;
				bool Admin = false;
				bool Integrity = false;
				bool Data = false;
				bool Ask = false;
				bool PlusGraphMenu = false;
				string sAbstract = "";
				string sView = "";
				string sAsk = "";
				string sAdmin = "";
				string sIntegrity = "";
				bool startOfData = false;
				foreach (string line in imenik)
				{
					string sTemp = line;
					if((sTemp.StartsWith("+") || sTemp.StartsWith("--")) && plus == false && indexList.Count == 0)
					{
						//sTemp = "iThis is a plus server\t(null)\terror.host\t0";
						plus = true;
						//i--;
					}
					
					if(plus)
					{
						//--------------------------------------------------------
						if(View)
						{
							if((line.ToLower().StartsWith(" ")))
							{
								sView = sView + line + crlf;
							}
							else
							{
								View=false;
								VIEWList.Add(sView);
								//LANGUAGEList.Add(sView);
								sView = "";
							}
						}
						if(Ask)
						{
							if((line.ToLower().StartsWith(" ")))
							{
								sAsk = sAsk + line + crlf;
							}
							else
							{
								Ask=false;
								ASKList.Add(sAsk);
								//LANGUAGEList.Add(sView);
								sAsk = "";
							}
						}
						if(Abstract)
						{
							if((line.ToLower().StartsWith(" ")))
							{
								//abstractBox.Text = abstractBox.Text + vrstica;
								sAbstract = sAbstract + line + crlf;
							}
							else
							{
								Abstract=false;
								ABSTRACTList.Add(sAbstract);
								sAbstract = "";
							}
						}
						if(Admin)
						{
							if((line.ToLower().StartsWith(" ")))
							{
								//abstractBox.Text = abstractBox.Text + vrstica;
								sAdmin = sAdmin + line + crlf;
							}
							else
							{
								Admin=false;
								ADMINList.Add(sAdmin);
								sAdmin = "";
							}
						}
						if(Integrity)
						{
							if((line.ToLower().StartsWith(" ")))
							{
								//abstractBox.Text = abstractBox.Text + vrstica;
								sIntegrity = sIntegrity + line + crlf;
								//MessageBox.Show(sIntegrity);
							}
							else
							{
								Integrity=false;
								INTEGRITYList.Add(sIntegrity);
								sIntegrity = "";
							}
						}
						if(Data)
						{
							rtfData.Add(line+crlf);
							//vrstica = "";
						}
						if(plus) i--;
						if(line.ToLower().StartsWith("+view"))
						{
							View = true;
							sView = (i).ToString()+"\t";
							//break;
						}
						if(line.ToLower().StartsWith("+ask"))
						{
							Ask = true;
							sAsk = (i).ToString()+"\t";
						}
						if(line.ToLower().StartsWith("+abstract"))
						{
							Abstract = true;
							sAbstract = (i).ToString()+"\t";
							//break;
						}
						if(line.ToLower().StartsWith("+admin:"))
						{
							//adminBox.Text = vrstica.Trim();
							Admin = true;
							sAdmin = (i).ToString()+"\t";
						}
						if(line.ToLower().StartsWith("+integrity:"))
						{
							//adminBox.Text = vrstica.Trim();
							Integrity = true;
							sIntegrity = (i).ToString()+"\t";
						}
						if(line.StartsWith("+MENU:"))
						{
							PlusGraphMenu = true;
						}
						if(line.ToLower().TrimStart().StartsWith("+data:"))
						{
							Data = true;
						}
						if(plus) i++;
						
						//--------------------------------------------------------
						
						if(sTemp.StartsWith("+ADMIN")){sTemp="";}
						else if(sTemp.StartsWith("+VIEWS")){sTemp="";}
						else if(sTemp.StartsWith("+ASK")){sTemp="";}
						else if(sTemp.StartsWith("+ABSTRACT")){sTemp="";}
						else if(sTemp.StartsWith("+INTEGRITY")){sTemp="";}
						else if(sTemp.TrimStart().StartsWith("+MENULINE"))
						{
							rtfLinks.Add(sTemp);
							sTemp="";
						}
						else if(sTemp.StartsWith("+DATA")){sTemp="";}
						
						else if(sTemp.TrimStart().StartsWith("+INFO"))
						{
							//MessageBox.Show(sTemp);
							sTemp=sTemp.Replace("+INFO: ", string.Empty).TrimStart();
							if(PlusGraphMenu)
							{
								//MessageBox.Show("DODAJAM SELEKTOR!");
								rtfSelectors.Add(sTemp);
							}
						}
						else if(sTemp.StartsWith(" ")){sTemp="";}
						else if(sTemp.StartsWith("+")){sTemp="";}
						else if(sTemp.StartsWith("-")){sTemp="";}
					}
					#region testing ...
//					StreamWriter SW = new StreamWriter("test.txt");
//					foreach(string test in ADMINList)
//					{
//						SW.WriteLine(test);
//					}
//					foreach(string test in ABSTRACTList)
//					{
//						SW.WriteLine(test);
//					}
//					foreach(string test in VIEWList)
//					{
//						SW.WriteLine(test);
//					}
//					foreach(string test in INTEGRITYList)
//					{
//						SW.WriteLine(test);
//					}
//					foreach(string test in ASKList)
//					{
//						SW.WriteLine(test);
//					}
//					SW.Flush();
//					SW.Close();
					#endregion
					
					if(sTemp.StartsWith("{\\rtf")) startOfData = true;
					if((sTemp.StartsWith("+-") == false) && (sTemp != string.Empty) && (startOfData == false))
					{
						if(sTemp.Contains("\t"))
						{
							char[] charSeparators = new char[] {'\t'};
							indexList.Add(i);
							infoList.Add(sTemp.Split(charSeparators, System.StringSplitOptions.None)[0].ToCharArray()[0].ToString());
							descList.Add(sTemp.Split(charSeparators, System.StringSplitOptions.None)[0].Substring(1,sTemp.Split(charSeparators, System.StringSplitOptions.None)[0].Length-1));
							selectList.Add(sTemp.Split(charSeparators, System.StringSplitOptions.None)[1]);
							addressList.Add(sTemp.Split(charSeparators, System.StringSplitOptions.None)[2]);
							portList.Add(sTemp.Split(charSeparators, System.StringSplitOptions.None)[3]);
							try
							{
								plusList.Add(sTemp.Split(charSeparators, System.StringSplitOptions.None)[4]);
							}
							catch(Exception)
							{
								plusList.Add(string.Empty);
							}
						}
						else
						{
							indexList.Add(i);
							infoList.Add("3");
							if(plus == false)
							{
								descList.Add(sTemp.Substring(1));
							}
							else
							{
								descList.Add(sTemp);	//pri plusu ni treba odstranit substringa
							}
							selectList.Add("");
							addressList.Add("");
							portList.Add("");
							plusList.Add("");
						}
						i++;
					}
				}
				
				foreach (int myItem in indexList)
				{
					#region items
					StringBuilder SBPredmet = new StringBuilder();
					if(plusList[myItem].StartsWith("?"))
					{
						SBPredmet.Append("[ask] ");
					}
					else if (infoList[myItem] == "i")
					{
						SBPredmet.Append("[inf] ");
					}
					else if (infoList[myItem] == "0")
					{
						SBPredmet.Append("[fil] ");
					}
					else if (infoList[myItem] == "1")
					{
						SBPredmet.Append("[dir] ");
					}
					else if (infoList[myItem] == "2")
					{
						SBPredmet.Append("[CSO] ");
					}
					else if (infoList[myItem] == "3")
					{
						SBPredmet.Append("[ERR] ");
					}
					else if (infoList[myItem] == "4")
					{
						SBPredmet.Append("[HEX] ");
					}
					else if (infoList[myItem] == "5")
					{
						SBPredmet.Append("[DOS] ");
					}
					else if (infoList[myItem] == "6")
					{
						SBPredmet.Append("[UUE] ");
					}
					else if (infoList[myItem] == "7")
					{
						SBPredmet.Append("[ ? ] ");
					}
					else if (infoList[myItem] == "8")
					{
						SBPredmet.Append("[ T ] ");
					}
					else if (infoList[myItem] == "9")
					{
						SBPredmet.Append("[bin] ");
					}
					else if (infoList[myItem] == "+")
					{
						SBPredmet.Append("[ds+] ");
					}
					else if (infoList[myItem] == "g")
					{
						SBPredmet.Append("[gif] ");
					}
					else if (infoList[myItem] == "h")
					{
						SBPredmet.Append("[htm] ");
					}
					else if (infoList[myItem] == "I")
					{
						SBPredmet.Append("[IMG] ");
					}
					else if (infoList[myItem] == "T")
					{
						SBPredmet.Append("[TN3] ");
					}
					else if (infoList[myItem] == "P")
					{
						SBPredmet.Append("[pdf] ");
					}
					else if (infoList[myItem] == "d")
					{
						SBPredmet.Append("[pdf] ");
					}
					else if (infoList[myItem] == "s")
					{
						SBPredmet.Append("[snd] ");
					}
					else if (infoList[myItem] == ";")
					{
						SBPredmet.Append("[mov] ");
					}
					else if (infoList[myItem] == "M")
					{
						SBPredmet.Append("[MIM] ");
					}
					else if (infoList[myItem] == "p")
					{
						SBPredmet.Append("[png] ");
					}
					else
					{
						SBPredmet.Append("["+infoList[myItem]+"  ] ");
					}
					gopherMenu.Items.Add(SBPredmet.ToString()+descList[myItem]);
					printSB.AppendLine(descList[myItem]);
					#endregion
				}
				
				if(rtfData.Count > 0)
				{
					StringBuilder SBRtf = new StringBuilder();
					foreach(string line in rtfData)
					{
						SBRtf.Append(line);
					}
					try
					{
						richTextBox.Rtf = SBRtf.ToString();
						
						splitContainerContent.Panel2Collapsed = false;
						//Data = false;
						
						foreach(string link in rtfLinks)
						{
							//richTextBox.AppendText(link+crlf);
							
							string[] parts = link.TrimStart().Split((" ").ToCharArray());
							//MessageBox.Show(deli[1]);
							int vrstica = Convert.ToInt32(parts[1]);
							//richTextBox.Lines[Convert.ToInt32(deli[1])]=richTextBox.Lines[Convert.ToInt32(deli[1])].Insert(Convert.ToInt32(deli[4]), "ftp://ftp.bio.indiana.edu");
							int start = richTextBox.GetFirstCharIndexFromLine(vrstica)+Convert.ToInt32(parts[2]);
							int end = richTextBox.GetFirstCharIndexFromLine(Convert.ToInt32(parts[3]))+Convert.ToInt32(parts[4]);
							int length = end-start;
							richTextBox.Select(start, length);
							richTextBox.SelectionColor = Color.Red;
							richTextBox.Select(end, 0);
							//richTextBox.
							//richTextBox.Lines[vrstica]="mmmmmmmmmm";
							//richTextBox.Lines[vrstica].Substring(0,Convert.ToInt32(deli[4]))+"mmmmmm"+richTextBox.Lines[vrstica].Substring(0,Convert.ToInt32(deli[4])+1);
							//MessageBox.Show(richTextBox.Lines[vrstica]);
						}
					}
					catch(Exception rtfExc)
					{
						MessageBox.Show("Error in RTF Data"+Environment.NewLine+Environment.NewLine+rtfExc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
			}
			catch (Exception e)
			{
				MessageBox.Show("Unable to establish connection"+Environment.NewLine+Environment.NewLine+e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			
			CleanHistory();
			foreach (string Zgodovina in descHist)
			{
				historyButton.DropDownItems.Add(Zgodovina);
			}
			
		}
		
		void connectButtonClick(object sender, EventArgs e)
		{
			DodajZgodovino(selectorBox.Text, selectorBox.Text, serverBox.Text, portBox.Text);
			getDirectory(selectorBox.Text, serverBox.Text, portBox.Text/*, iTimeout*/);
		}
		
		void infoButtonClick(object sender, EventArgs e)
		{
			//UriBuilder UB = new UriBuilder("gopher://gopher.floodgap.com:70/0/gopher/proxy");

			//MessageBox.Show(arguments[0]);
			try
			{
				MessageBox.Show("Index: "+indexList[gopherMenu.SelectedIndex]+Environment.NewLine+
				                                     "Info ID: "+infoList[gopherMenu.SelectedIndex]+Environment.NewLine+
				                                     "Descriptor: "+descList[gopherMenu.SelectedIndex]+Environment.NewLine+
				                                     "Selector: "+selectList[gopherMenu.SelectedIndex]+Environment.NewLine+
				                                     "Server: "+addressList[gopherMenu.SelectedIndex]+Environment.NewLine+
				                                     "Port: "+portList[gopherMenu.SelectedIndex]+Environment.NewLine+
				                                     "Plus: "+plusList[gopherMenu.SelectedIndex],
				                                     descList[gopherMenu.SelectedIndex], MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			catch (Exception InfoE)
			{
				MessageBox.Show("Before clicking Info button, you need to get the menu from the server"+Environment.NewLine+Environment.NewLine+InfoE.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		
		void gopherMenuDoubleClick(object sender, EventArgs e)
		{
			try
			{
				this.Cursor = Cursors.WaitCursor;
				handleGopherRequest(plusList[gopherMenu.SelectedIndex],
				                    infoList[gopherMenu.SelectedIndex],
				                    selectList[gopherMenu.SelectedIndex],
				                    addressList[gopherMenu.SelectedIndex],
				                    portList[gopherMenu.SelectedIndex],
				                    descList[gopherMenu.SelectedIndex]);
				if(doAsk)
				{
					try
					{
						processAskRequest(infoList[gopherMenu.SelectedIndex]);
					}
					catch(Exception)
					{}
					doAsk = false;
				}
				this.Cursor = Cursors.Default;
			}
			catch(Exception)
			{
				//TODO: add the exception ...
			}
			
		}
		
		void processAskRequest(string itemType)
		{
			try
			{
				if(itemType == "1")
				{
					if(askMenu.Count > 0)
					{
						Cleanup();
						writeDirectory(askMenu);
					}
					else
					{
						MessageBox.Show("No data");
					}
				}
				else if(itemType == "0")
				{
					if(askMenu.Count > 0)
					{
						TekstovnoOkno to = new TekstovnoOkno("null", "null", "null", 0);
						//MessageBox.Show(askMenu[0]+askMenu[1]+askMenu[2]);
						to.vrstice = askMenu;
						to.Show();
					}
					else
					{
						MessageBox.Show("No data");
					}
				}
			}
			catch(Exception e)
			{
				MessageBox.Show(e.Message);
			}
		}
		
		void handleGopherRequest(string paramPlus,
		                         string paramInfo,
		                         string paramSelector,
		                         string paramAddress,
		                         string paramPort,
		                         string paramDeskriptor)
		{
			try
			{
				#region nonplus selector
				// Če ni plus selektor
				if((paramPlus == "") ||
				   (plusUse.CheckState == CheckState.Unchecked))// ||
					//   ((plusViews.Count == 0) && (paramPlus != "?")) ||
					//   (paramPlus.StartsWith("+") == false))
				{
					//MessageBox.Show("to je to");
					if(paramInfo == "1")
					{
						//imenik
						selectorBox.Text = paramSelector;
						serverBox.Text = paramAddress;
						portBox.Text = paramPort;
						DodajZgodovino(paramDeskriptor, paramSelector, paramAddress, paramPort);
						getDirectory(paramSelector, paramAddress, paramPort/*, iTimeout*/);
					}
					else if(paramInfo == "0")
					{
						//tekstovna datoteka
						TekstovnoOkno tekstOkno = new TekstovnoOkno(paramSelector, paramAddress, paramPort, waitTimeout);
						tekstOkno.ShowInTaskbar = false;
						tekstOkno.ShowDialog();
					}
					else if(paramInfo == "7")
					{
						//iskanje po strežniku
						iskanjePoStrezniku search = new iskanjePoStrezniku();
						if(search.ShowDialog() == DialogResult.OK)
						{
							DodajZgodovino(paramDeskriptor+" ("+search.iskanje+")", paramSelector+"\t"+search.iskanje, paramAddress, paramPort);
							getDirectory(paramSelector+"\t"+search.iskanje, paramAddress, paramPort/*, iTimeout*3*/);
						}
					}
					else if(paramInfo == "i")
					{
						//ne naredimo nič - informacije
					}
					else if(paramInfo == "3")
					{
						//ne naredimo nič - napaka
					}
					else if(paramInfo == "8")
					{
						//telnet
						System.Diagnostics.Process.Start("telnet.exe", paramAddress+" "+paramPort);
					}
					else if(paramInfo == "2")
					{
						//Telefonski imenik
						ImenikOkno imenik = new ImenikOkno(paramSelector, paramAddress, paramPort, waitTimeout);
						imenik.Show();
					}
					else if(paramInfo == "h")
					{
						//Spletna stran
						WebViewer webview = new WebViewer(paramSelector, paramAddress, paramPort, waitTimeout, downloadsFolder);
						webview.Show();
					}
					else
					{
						DolPotegniPredmet(paramSelector, paramAddress, paramPort, "", ""); //empty plusString and integrity string
					}
				}
				#endregion
				// je plus selektor
				#region plus selector
				else
				{
					
//					else
//					{
					plusClean();
//						try
//						{
					if(selectorBox.Text.Contains("\t$"))
					{
						getPlusInfoNov2(gopherMenu.SelectedIndex);
						if(plusViews.Count == 0)
						{
							getPlusInfoNov(paramSelector, paramAddress, paramPort);
						}
					}
					else
					{
						getPlusInfoNov(paramSelector, paramAddress, paramPort);
					}
					if(paramPlus.StartsWith("?"))
					{
						//MessageBox.Show(plusAsk[0]);
						try
						{
							Ask ask = new Ask(paramSelector, paramAddress, paramPort, waitTimeout);
							if(plusAsk.Count > 0)
							{
								ask.askStrings = plusAsk;
							}
							if(ask.ShowDialog() == DialogResult.Cancel)
							{
								return;
							}
							else
							{
								doAsk = true;
								askMenu = ask.rezultat;
								return;
							}
						}
						catch(Exception AskEx)
						{
							MessageBox.Show("Problem with Ask form ..."+Environment.NewLine+Environment.NewLine+AskEx.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return;
						}
					}
					#region not_used
					
//							if(plusViews.Count == 0)
//							{
//								plusViews.Add(" ");
//							}
//						}
//						catch(Exception ex)
//						{
//							MessageBox.Show("Error retriving menu\n\n"+ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//						}
					#endregion
					//PlusButtonClick(sender, e);
					//splitContainer1.Panel2Collapsed = false;
					int indexJezika = 0;
					bool jezikKonec = false;
					if(plusLanguages.Count != 0)
					{
						foreach(string jezik in listOfLanguages)
						{
							if(jezikKonec) break;
							foreach(string mojjezik in plusLanguages)
							{
								if(jezik.ToLower() == mojjezik.ToLower())
								{
									MessageBox.Show(jezik +"="+ mojjezik);
									jezikKonec = true;
									break;
								}
								
								indexJezika++;
							}
						}
					}
					// TODO končaj to ... zadevo
					MessageBox.Show(indexJezika.ToString());
					
					string mimeMatch = "";
					bool defaultMime = false;
					int selectedView = 0;
					if(plusViews.Count != 0)
					{
						try
						{
							bool done = false;
							foreach(string format in listOfViews)
							{
								
								foreach(string view in plusViews)
								{
									if(done == false) selectedView++;
									if((format == view.ToLower().Trim()) && (done == false))
									{
										//MessageBox.Show(format+"+"+view);
										mimeMatch = view.ToLower().Trim();
										done = true;
										//MessageBox.Show(mimeMatch);
									}
								}
								if(done == false) selectedView = 0;
							}
							if(mimeMatch.ToLower().Trim() == plusViews[0].ToLower().Trim()) defaultMime = true;
							//MessageBox.Show(selectedView.ToString());
							#region not_used
//								StreamReader SR = new StreamReader("format.dat");
//								string format = "";
//
//								bool done = false;
//
//								while(SR.EndOfStream == false)
//								{
//									format = SR.ReadLine();
//									//if(plusViews.Count < 0)
//									//{
//									foreach(string view in plusViews)
//									{
//										if(done == false) selectedView++;
//										if((format == view.ToLower().Trim()) && (done == false))
//										{
//
//											//MessageBox.Show(format+"+"+view);
//											mimeMatch = view.ToLower().Trim();
//											done = true;
//										}
//											//
//									}
//									if(done == false) selectedView = 0;
//									//}
//									//else
//									//{
//									//	plusViews.Add("");
//									//}
//								}
//								SR.Close();
//								if(mimeMatch.ToLower().Trim() == plusViews[0].ToLower().Trim()) defaultMime = true;
//								//MessageBox.Show(defaultMime.ToString());
//								done = false;
							#endregion
						}
						catch(Exception ex1)
						{
							MessageBox.Show("Error retriving item's plus info!"+Environment.NewLine+Environment.NewLine+ex1.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
						}
						
						if((mimeMatch == "") && (plusViews.Count > 0))
						{
							if(MessageBox.Show("No file types available are on your prefered type list. Using:"+plusViews[0], "Info") == DialogResult.OK)
							{
								mimeMatch = plusViews[0].ToLower().Trim();
							}
						}
					}
					
					selectedView--;
					if(selectedView == -1) selectedView = 0;
					
					try
					{
						if((plusFileSizes[selectedView].Contains("na") == false) && (plusFileSizeWarning != 0))
						{
							float tempi = 0;
							string tempsi = plusFileSizes[selectedView];
							tempsi = tempsi.Replace("k", string.Empty);
							tempsi = tempsi.Replace("<", string.Empty);
							tempsi = tempsi.Replace(">", string.Empty);
							tempsi = tempsi.Replace(".", System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
							if(tempsi.StartsWith(System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)) tempsi = "0"+tempsi;
							tempi = float.Parse(tempsi, System.Globalization.NumberStyles.Float);
							if(tempi > plusFileSizeWarning)
							{
								if(MessageBox.Show("This item's size is "+tempi.ToString()+" kB. Procede?", "File Size Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
								{
									return;
								}
							}
						}
					}
					catch(Exception)
					{}
					
					
					//MessageBox.Show(selectedView.ToString()+"-"+plusViews[selectedView]+"-"+plusLanguages[selectedView]);
					//MessageBox.Show(plusLanguages[selectedView]+1);
					string mojJezik = "";
					bool done1 = false;
					string testLanguage = "";
					if(plusLanguages.Count > 0)
					{
						testLanguage = plusLanguages[selectedView];
					}
					testLanguage = testLanguage.ToLower();
					mojJezik = testLanguage;
					if(testLanguage != "na")
					{
						//string tempsJezik = "";
						foreach(string jezik in listOfLanguages)
						{
							if(testLanguage.Contains(jezik.ToLower()) && (done1==false))
							{
								mojJezik = jezik;
								done1 = true;
								//MessageBox.Show(mojJezik);
							}
						}
						selectedView = 0;
					}
					else mojJezik = "";
					/////////////////////////////////////////////////////////////

					
					
					/////////////////////////////////////////////////////////////
					try
					{
						string temps = mimeMatch;
						//if(mojJezik != "") temps = temps+" "+mojJezik;
						mojJezik = " "+mojJezik;
						//MessageBox.Show(temps);
						if (temps == ("application/gopher-menu") ||
						    temps == ("internet/gopher-menu") ||
						    (temps == ("directory/recursive")))
						{
							selectorBox.Text = paramSelector;
							serverBox.Text = paramAddress;
							portBox.Text = paramPort;
							DodajZgodovino(paramDeskriptor, paramSelector+"\t+"+temps+mojJezik, paramAddress, paramPort);
							getDirectory(paramSelector+"\t+"+temps+mojJezik, paramAddress, paramPort/*, iTimeout*/);
							//DobiImenik(paramSelector+"\t$", paramAddress, paramPort, iTimeout);
						}
						
						else if ((temps == ("application/gopher+-menu")) ||
						         (temps == ("internet/gopher+-menu")) ||
						         (paramInfo == "1") ||
						         (temps == ("directory+/recursive")))
						{
							//imenik
							selectorBox.Text = paramSelector;
							serverBox.Text = paramAddress;
							portBox.Text = paramPort;
							DodajZgodovino(paramDeskriptor, paramSelector+"\t$", paramAddress, paramPort);
							//DobiImenik(paramSelector+"\t+"+temps+mojJezik, paramAddress, paramPort, iTimeout);
							getDirectory(paramSelector+"\t$", paramAddress, paramPort/*, iTimeout*/);
						}
						else if (temps == ("text/plain"))
						{
							//tekstovna datoteka
							TekstovnoOkno tekstOkno = new TekstovnoOkno(paramSelector+"\t+"+temps+mojJezik, paramAddress, paramPort, waitTimeout);
							tekstOkno.ShowInTaskbar = false;
							tekstOkno.ShowDialog();
						}
						else if((paramInfo == "7") || (temps == "internet/gopher-query"))
						{
							//iskanje po strežniku
							iskanjePoStrezniku search = new iskanjePoStrezniku();
							if (search.ShowDialog() == DialogResult.OK)
							{
								DodajZgodovino(paramDeskriptor+" ("+search.iskanje+")", paramSelector+"\t"+search.iskanje, paramAddress, paramPort);
								getDirectory(paramSelector+"\t"+search.iskanje, paramAddress, paramPort/*, iTimeout*3*/);
							}
						}
						else if((paramInfo == "i") || (temps == "internet/gopher-note"))
						{
							//ne naredimo nič - informacije		+
						}
						else if((paramInfo == "3") || (temps == "internet/error"))
						{
							//ne naredimo nič - napaka
						}
						else if((paramInfo == "8") || (temps == "terminal/telnet") || (temps == "terminal/tn3270"))
						{
							//telnet
							System.Diagnostics.Process.Start("telnet.exe", paramAddress+" "+paramPort);
						}
						else if((paramInfo == "2") || (temps == "internet/cso"))
						{
							//Telefonski imenik
							ImenikOkno imenik = new ImenikOkno(paramSelector, paramAddress, paramPort, waitTimeout);
							imenik.Show();
						}
						else if (temps == ("text/html"))
						{
							//Spletna stran
							WebViewer webview = new WebViewer(paramSelector+"\t+"+temps+mojJezik, paramAddress, paramPort, waitTimeout, downloadsFolder);
							webview.Show();
						}
						else
						{
							if(defaultMime)
							{
								DolPotegniPredmet(paramSelector, paramAddress, paramPort, "\t+"+temps+mojJezik, plusIntegrity);
							}
							else
							{
								DolPotegniPredmet(paramSelector, paramAddress, paramPort, "\t+"+temps+mojJezik, "");
							}
						}
					}
					catch (Exception ex)
					{
						MessageBox.Show("Before clicking the menu, you need to get it from the server"+Environment.NewLine+Environment.NewLine+ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
//					}
				}
				#endregion
			}
			catch (Exception ex)
			{
				MessageBox.Show("Unable to handle the request."+Environment.NewLine+Environment.NewLine+ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				this.Cursor = Cursors.Default;
			}
		}
		
		void saveButtonClick(object sender, EventArgs e)
		{
			try
			{
				if (infoList[gopherMenu.SelectedIndex] == "3") {}
				else if (infoList[gopherMenu.SelectedIndex] == "i") {}
				else
				{
					DolPotegniPredmet(selectList[gopherMenu.SelectedIndex], addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], "", "");	// empty plusString
				}
				
			}
			catch (Exception dolpotegE)
			{
				MessageBox.Show("Before pressing this button, you need to get a menu from the server"+Environment.NewLine+Environment.NewLine+dolpotegE.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		
		void DolPotegniPredmet(string selector, string address, string port, string plusString, string integrity)
		{
			DownloadThread downloader = new DownloadThread(selector+plusString, address, port, integrity, settingsDir);
			Thread DownloadThread = new Thread(new ThreadStart(downloader.ThreadFunction));
			DownloadThread.Start();
		}
		
		void gopherMenuKeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
			{
				gopherMenuDoubleClick(sender, e);
			}
		}
		
		void AboutToolStripMenuItemClick(object sender, EventArgs e)
		{
			oProgramu aboutBox = new oProgramu();
			aboutBox.ShowDialog();
		}
		
		void DodajZgodovino(string deskriptor, string selektor, string streznik, string vrata)
		{
			if (deskriptor.Trim()=="")
			{
				descHist.Add("Title Page");
			}
			else
			{
				descHist.Add(deskriptor);
			}
			selectHist.Add(selektor);
			addressHist.Add(streznik);
			portHist.Add(vrata);
		}
		
		void DodajStatus(string selektor, string streznik, string vrata)
		{
			selectorBox.Text = selektor;
			serverBox.Text = streznik;
			portBox.Text = vrata;
		}
		
		void historyButtonDropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
		{
			Cleanup();
			int mojIndex = historyButton.DropDownItems.IndexOf(e.ClickedItem);
			getDirectory(selectHist[mojIndex], addressHist[mojIndex], portHist[mojIndex]/*, iTimeout*/);
		}
		
		void ContentsToolStripMenuItemClick(object sender, EventArgs e)
		{
			Help.ShowHelp(this, Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\"))+"\\Help\\gopher.chm", "html\\index.htm");
			//Help.ShowHelp(this, Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\"))+"\\Help\\gopher1.chm", "html\\2text-window.htm");
			//Help.ShowHelpIndex(this, Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\"))+"\\Help\\gopher1.chm");
		}
		
		void printToolStripMenuItem_Click(object sender, EventArgs e)
		{
			PrintDialog pd = new PrintDialog();
			_printdocument.Text = printSB.ToString();
			_printdocument.Font = gopherMenu.Font;
			pd.Document = _printdocument;
			if (pd.ShowDialog() == DialogResult.OK)
			{
				try
				{
					_printdocument.Print();
				}
				catch (Exception printException)
				{
					MessageBox.Show("Printing error."+Environment.NewLine+Environment.NewLine+printException.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}

		void pripravaStraniToolStripMenuItem_Click(object sender, EventArgs e)
		{
			PageSetupDialog psd = new PageSetupDialog();
			psd.Document = _printdocument;
			psd.ShowDialog();
		}

		void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
		{
			PrintPreviewDialog ppd = new PrintPreviewDialog();
			_printdocument.Text = printSB.ToString();
			_printdocument.Font = gopherMenu.Font;
			ppd.Document = _printdocument;
			ppd.ShowDialog();
		}

		void saveToolStripMenuItem_Click(object sender, EventArgs e)
		{
			SaveFileDialog saveDialog = new SaveFileDialog();
			saveDialog.Filter = ("Text file (*.txt)|*.txt|All files (*.*)|*.*");
			if (saveDialog.ShowDialog() == DialogResult.OK)
			{
				StreamWriter sw = new StreamWriter(saveDialog.FileName);
				sw.Write(printSB.ToString());
				sw.Close();
			}
		}
		
		void printButtonClick(object sender, EventArgs e)
		{
			printToolStripMenuItem_Click(sender,e);
		}
		
		void searchButtonClick(object sender, EventArgs e)
		{
			Cleanup();
			DodajZgodovino("Search: " + searchBox.Text, searchSelector + searchBox.Text, searchServer, searchPort);
			getDirectory(searchSelector + searchBox.Text, searchServer, searchPort/*, iTimeout*3*/);
			gopherMenu.Focus();
		}
		
		void CustomizeToolStripMenuItemClick(object sender, EventArgs e)
		{
			SettingsDialog settingsDialog = new SettingsDialog();
			if(settingsDialog.ShowDialog() == DialogResult.OK)
			{
				ReloadSettings(true);
			}
		}

		void MainFormLoad(object sender, EventArgs e)
		{
			//this.Text = Resources.Culture.EnglishName;
			
			try
			{
				//CustomRenderer cr = new CustomRenderer();
				//ToolStripManager.Renderer = cr;
				RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
				settingsFile = key.GetValue("AppData").ToString()+"\\Gopher\\settings.xml";
				favouritesFile = key.GetValue("AppData").ToString()+"\\Gopher\\favourites.xml";
				settingsDir = key.GetValue("AppData").ToString()+"\\Gopher\\";
				
				
				/*
				settingsDir = "/Users/matjaz/mGopher/settings/";
				favouritesFile ="/Users/matjaz/mGopher/settings/favourites.xml";
				settingsFile = "/Users/matjaz/mGopher/settings/settings.xml";
				*/
			
				ReloadSettings(false);
				ReloadFavourites();
				if(arguments.Length > 0)
				{
					doUrl(arguments[0], sender, e);
				}
			}
			catch(Exception)
			{}
		}
		
		void doUrl(string urlAddress, object sender, EventArgs e)
		{
			//MessageBox.Show(urlAddress);
			try
			{
				UriBuilder UB = new UriBuilder(urlAddress);
				if(UB.Scheme == Uri.UriSchemeGopher)
				{
					string mojSelektor = Uri.UnescapeDataString(UB.Path);
					string[] deliSelektorja = mojSelektor.Split("\t".ToCharArray());
					
					//MessageBox.Show(deliSelektorja.Length.ToString());
					
					if(deliSelektorja.Length == 1)
					{
						if(UB.Path.Length > 3)
						{
							handleGopherRequest("",
							                    deliSelektorja[0][1].ToString(),
							                    deliSelektorja[0].Substring(2),
							                    UB.Host,
							                    UB.Port.ToString(),
							                    Uri.UnescapeDataString(deliSelektorja[0]));
						}
						else
						{
							handleGopherRequest("",
							                    "1",
							                    "",
							                    UB.Host,
							                    UB.Port.ToString(),
							                    UB.Host);
						}
					}
					else if(deliSelektorja.Length == 2)
					{
						if((UB.Path.Length > 3) && (deliSelektorja[1] == string.Empty))
						{
							handleGopherRequest("",
							                    deliSelektorja[0][1].ToString(),
							                    deliSelektorja[0].Substring(2)+"\t"+deliSelektorja[1],
							                    UB.Host,
							                    UB.Port.ToString(),
							                    Uri.UnescapeDataString(UB.Path));
						}
						else if((UB.Path.Length > 3) && (deliSelektorja[1] != string.Empty))
						{
							handleGopherRequest("",
							                    "1",
							                    deliSelektorja[0].Substring(2)+"\t"+deliSelektorja[1],
							                    UB.Host,
							                    UB.Port.ToString(),
							                    Uri.UnescapeDataString(UB.Path));
						}
					}
					else if(deliSelektorja.Length == 3)
					{
						if((UB.Path.Length > 3) && (deliSelektorja[1] == string.Empty) && (deliSelektorja[0][1].ToString() == "7"))
						{
							handleGopherRequest(deliSelektorja[2],
							                    deliSelektorja[0][1].ToString(),
							                    deliSelektorja[0].Substring(2)+"\t"+deliSelektorja[1],
							                    UB.Host,
							                    UB.Port.ToString(),
							                    Uri.UnescapeDataString(UB.Path));
						}
						else if((UB.Path.Length > 3) && (deliSelektorja[1] != string.Empty))
						{
							handleGopherRequest(deliSelektorja[2],
							                    "1",
							                    deliSelektorja[0].Substring(2)+"\t"+deliSelektorja[1],
							                    UB.Host,
							                    UB.Port.ToString(),
							                    Uri.UnescapeDataString(UB.Path));
						}
						else if((UB.Path.Length > 3) && (deliSelektorja[1] == string.Empty) && (deliSelektorja[0][1].ToString() != "7"))
						{
							handleGopherRequest(deliSelektorja[2],
							                    deliSelektorja[0][1].ToString(),
							                    deliSelektorja[0].Substring(2),
							                    UB.Host,
							                    UB.Port.ToString(),
							                    Uri.UnescapeDataString(deliSelektorja[0]));
						}
						else
						{
							handleGopherRequest(deliSelektorja[2],
							                    "1",
							                    "",
							                    UB.Host,
							                    UB.Port.ToString(),
							                    UB.Host);
						}
					}
				}
				else
				{
					MessageBox.Show("hej");
					WebViewer wv = new WebViewer("URL:"+urlAddress, "localhost", "7070", waitTimeout, downloadsFolder);
					wv.ShowDialog();
					wv.Dispose();
				}
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
		
		void ReloadSettings(bool preserveButtons)
		{
			bool mPlus = (plusRefresh.CheckState == CheckState.Checked);
			bool nPlus = (plusUse.CheckState == CheckState.Checked);
			
			try
			{
				DataSet ds = new DataSet();
				ds.ReadXml(settingsFile);
				DataRow dr = ds.Tables[0].Rows[0];
				
				waitTimeout = Convert.ToInt32(dr["timeout"].ToString());
				homeServer = dr["server"].ToString();
				homeSelector = dr["selector"].ToString();
				homePort = dr["port"].ToString();
				downloadsFolder = dr["downloads"].ToString();
				searchServer = dr["searchServer"].ToString();
				searchSelector = dr["searchSelector"].ToString();
				searchPort = dr["searchPort"].ToString();
				plusOn = dr["plusOn"].ToString();
				plusRefreshOn = dr["plusRefreshOn"].ToString();
				plusFileSizeWarning = Convert.ToInt32(dr["plusFileSizeWarning"].ToString());
			}
			catch(Exception emoja)
			{
				MessageBox.Show(emoja.Message);
				SettingsDialog settingsDialog = new SettingsDialog();
				settingsDialog.Show();
			}
			if(preserveButtons == false)
			{
				serverBox.Text = homeServer;
				selectorBox.Text = homeSelector;
				portBox.Text = homePort;
			}
			
			if(plusOn == "on")
			{
				plusUse.CheckState = CheckState.Checked;
			}
			else
			{
				plusUse.CheckState = CheckState.Unchecked;
				plusOn = "off";
			}
			if(plusRefreshOn == "on")
			{
				plusRefresh.CheckState = CheckState.Checked;
			}
			else
			{
				plusRefresh.CheckState = CheckState.Unchecked;
				plusRefreshOn = "off";
			}
			//naložimo jezike
			listOfLanguages.Clear();
			StreamReader SR = new StreamReader(settingsDir+"languages.dat");
			string temps = "";
			while(SR.EndOfStream == false)
			{
				temps = SR.ReadLine();
				listOfLanguages.Add(temps.Substring(0,temps.IndexOf(";")).Trim());
			}
			SR.Close();
			listOfViews.Clear();
			SR = new StreamReader(settingsDir+"format.dat");
			while(SR.EndOfStream == false)
			{
				listOfViews.Add(SR.ReadLine().Trim());
			}
			SR.Close();
			if(preserveButtons)
			{
				if(mPlus)
				{
					plusRefresh.CheckState = CheckState.Checked;
				}
				else
				{
					plusRefresh.CheckState = CheckState.Unchecked;
				}
				if(nPlus)
				{
					plusUse.CheckState = CheckState.Checked;
				}
				else
				{
					plusUse.CheckState = CheckState.Unchecked;
				}
			}
		}
		
		void GopherMenuSelectedIndexChanged(object sender, EventArgs e)
		{
			try
			{
				Status.Text = ("Item ID: "+infoList[gopherMenu.SelectedIndex]+" - "+
				               "Selector: "+selectList[gopherMenu.SelectedIndex]+" - "+
				               "Server: "+addressList[gopherMenu.SelectedIndex]+" - "+
				               "Port: "+portList[gopherMenu.SelectedIndex]);
				if((plusList[gopherMenu.SelectedIndex] == "") || (plusRefresh.Checked == false))
				{
					splitContainer.Panel2Collapsed = true;
				}
				else
				{
					plusClean();
					try
					{
//						Thread th = new Thread(new ThreadStart(getPlusInfo));
//						th.Start();
						getPlusInfoNov(selectList[gopherMenu.SelectedIndex], addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex]);
					}
					catch(Exception ex)
					{
						MessageBox.Show(ex.Message, "Error");
					}
					//PlusButtonClick(sender, e);
					splitContainer.Panel2Collapsed = false;
				}
			}
			catch (Exception)
			{

			}
		}
		
		void MainFormHelpRequested(object sender, HelpEventArgs hlpevent)
		{
			Help.ShowHelp(this, Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\"))+"\\Help\\gopher.chm", "html\\main-window.htm");
		}
		
		void SearchBoxKeyDown(object sender, KeyEventArgs e)
		{
			if(e.KeyCode == Keys.Return)
			{
				searchButtonClick(sender, e);
			}
		}
		
		void HomeButtonClick(object sender, EventArgs e)
		{
			Cleanup();
			DodajZgodovino("Home", homeSelector, homeServer, homePort);
			getDirectory(homeSelector, homeServer, homePort/*, iTimeout*/);
		}
		
		void GopherMenuDrawItem(object sender, DrawItemEventArgs e)
		{
			#region barve za menu
			e.DrawBackground();
			Brush myBrush = Brushes.Black;
			SolidBrush brush = new SolidBrush( Color.Red );
			Image image;
			
			//if(Environment.OSVersion.Platform.ToString()=="Win32NT");
			//if(Environment.OSVersion.Version.ToString().StartsWith("6.0"))
			{
				if(e.Index % 2 == 0)
				{
					brush.Color = Color.FromArgb(255,211,232,213);
				}
				else
				{
					brush.Color = Color.FromArgb(255,238,236,239);
				}
				if(e.State.ToString().ToLower().Contains("selected") &&
				   e.State.ToString().ToLower().Contains("focus"))
				{
					brush.Color = Color.PaleGreen;
				}
				e.Graphics.FillRectangle( brush, e.Bounds );
			}

			if(e.Index > -1)
			{
				try
				{
					switch (((ListBox)sender).Items[e.Index].ToString().Substring(0,5))
					{
						case "[inf]":
							myBrush = Brushes.Green;
							//image = new Bitmap("info.png");
							image = menuImageList.Images[7];
							break;
						case "[dir]":
							myBrush = Brushes.Orange;
							image = menuImageList.Images[2];
							break;
						case "[fil]":
							myBrush = Brushes.Purple;
							image = menuImageList.Images[16];
							break;
						case "[ ? ]":
							myBrush = Brushes.Blue;
							image = menuImageList.Images[12];
							break;
						case "[bin]":
							myBrush = Brushes.BlueViolet;
							image = menuImageList.Images[1];
							break;
						case "[ERR]":
							myBrush = Brushes.Red;
							image = menuImageList.Images[3];
							break;
						case "[pdf]":
							myBrush = Brushes.DarkKhaki;
							image = menuImageList.Images[0];
							break;
						case "[CSO]":
							myBrush = Brushes.Indigo;
							image = menuImageList.Images[10];
							break;
						case "[ds+]":
							myBrush = Brushes.LightGray;
							image = menuImageList.Images[11];
							break;
						case "[htm]":
							myBrush = Brushes.Olive;
							image = menuImageList.Images[19];
							break;
						case "[HEX]":
							myBrush = Brushes.YellowGreen;
							image = menuImageList.Images[5];
							break;
						case "[DOS]":
							myBrush = Brushes.Violet;
							image = menuImageList.Images[20];
							break;
						case "[UUE]":
							myBrush = Brushes.SeaGreen;
							image = menuImageList.Images[18];
							break;
						case "[ T ]":
							myBrush = Brushes.Cyan;
							image = menuImageList.Images[14];
							break;
						case "[gif]":
							myBrush = Brushes.HotPink;
							image = menuImageList.Images[4];
							break;
						case "[IMG]":
						case "[png]":
							myBrush = Brushes.DimGray;
							image = menuImageList.Images[6];
							break;
						case "[TN3]":
							myBrush = Brushes.Wheat;
							image = menuImageList.Images[15];
							break;
						case "[snd]":
							myBrush = Brushes.DarkOrange;
							image = menuImageList.Images[13];
							break;
						case "[mov]":
							myBrush = Brushes.ForestGreen;
							image = menuImageList.Images[9];
							break;
						case "[MIM]":
							myBrush = Brushes.MediumSeaGreen;
							image = menuImageList.Images[8];
							break;
						case "[ask]":
							myBrush = Brushes.DarkBlue;
							image = menuImageList.Images[21];
							break;
						default:
							myBrush = Brushes.Black;
							image = menuImageList.Images[17];
							break;
					}
					
					Rectangle rectImage = new Rectangle(e.Bounds.X+1, e.Bounds.Y+1, e.Bounds.Width-2, e.Bounds.Height-2);
					
					rectImage.Width = (int) Math.Round(image.Width * ((double) e.Bounds.Height / image.Height));
					e.Graphics.DrawImage(image, rectImage);
					
					e.Graphics.DrawString("  "+((ListBox)sender).Items[e.Index].ToString().Substring(5),
					                      e.Font, myBrush,e.Bounds,StringFormat.GenericDefault);
				}
				catch(Exception eMenu)
				{
					MessageBox.Show(eMenu.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
			
			e.DrawFocusRectangle();
			#endregion
		}
		// Favourites
		void FavouritesGoButtonClick(object sender, EventArgs e)
		{
			// nalaganje favorites
			XmlTextReader xtr = null;
			//string favouritesFile = "favourites.xml";
			try
			{
				xtr = new XmlTextReader(favouritesFile);
				xtr.WhitespaceHandling = WhitespaceHandling.None;

				while(xtr.Read())
				{
					switch(xtr.NodeType)
					{
						case XmlNodeType.Element:
							{
								if(xtr.Name == "item")
								{
									if(xtr.GetAttribute("name") == favouritesBox.SelectedItem.ToString())
									{
										if(xtr.GetAttribute("type") == "0")
										{
											DodajZgodovino("Favourites: "+xtr.GetAttribute("name"), xtr.GetAttribute("selector")+xtr.GetAttribute("plus"), xtr.GetAttribute("server"), xtr.GetAttribute("port"));
											getDirectory(xtr.GetAttribute("selector")+xtr.GetAttribute("plus"), xtr.GetAttribute("server"), xtr.GetAttribute("port")/*, iTimeout*/);
										}
										//favouritesBox.Items.Add(xtr.GetAttribute("name"));
									}
								}
								break;
							}
					}
					//favouritesBox.SelectedIndex = 1;
				}
			}
			catch(Exception e2)
			{
				MessageBox.Show("Cannot read Favourites file: "+ favouritesFile+Environment.NewLine+Environment.NewLine+e2.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				if(xtr != null)
				{
					xtr.Close();
				}
			}
			gopherMenu.Focus();
		}
		
		void FavouritesAddButtonClick(object sender, EventArgs e)
		{
			FavouriteName fn = new FavouriteName(favouritesFile, serverBox.Text, portBox.Text, selectorBox.Text, "", "0");
			fn.ShowDialog();
			ReloadFavourites();
		}
		
		void FavouritesRemoveButtonClick(object sender, EventArgs e)
		{
			try
			{
				XmlDocument doc = new XmlDocument();
				doc.Load(favouritesFile);
				XmlNode xn = doc.SelectSingleNode("/favourites/item");
				while(xn.Attributes.GetNamedItem("name").InnerText != favouritesBox.Text)
				{
					xn = xn.NextSibling;
				}
				if(MessageBox.Show("You are about to delete "+xn.Attributes.GetNamedItem("name").InnerText+". Continue?","Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
				{
					xn.ParentNode.RemoveChild(xn);
					doc.Save(favouritesFile);
					ReloadFavourites();
				}
			}
			catch(Exception)
			{}
		}
		
		void FavouritesBoxKeyDown(object sender, KeyEventArgs e)
		{
			if(e.KeyCode == Keys.Return)
			{
				FavouritesGoButtonClick(sender, e);
			}
		}
		
		void ReloadFavourites()
		{
			favouritesBox.Items.Clear();
			// nalaganje favorites
			XmlTextReader xtr = null;
			//string favouritesFile = "favourites.xml";
			try
			{
				xtr = new XmlTextReader(favouritesFile);
				xtr.WhitespaceHandling = WhitespaceHandling.None;

				while(xtr.Read())
				{
					switch(xtr.NodeType)
					{
						case XmlNodeType.Element:
							{
								if(xtr.Name == "item")
								{
									favouritesBox.Items.Add(xtr.GetAttribute("name"));
								}
								
								break;
							}
					}
					//favouritesBox.SelectedIndex = 1;
				}
			}
			catch(Exception)
			{
				SettingsDialog sd = new SettingsDialog();
				sd.ShowDialog();
			}
			finally
			{
				if(xtr != null)
				{
					xtr.Close();
				}
			}
			
		}
		
		void FavouritesReloadButtonClick(object sender, EventArgs e)
		{
			ReloadFavourites();
		}
		
		void ReloadButtonClick(object sender, EventArgs e)
		{
			Cleanup();
			getDirectory(selectorBox.Text, serverBox.Text, portBox.Text/*, iTimeout*/);
		}
		
		void PlusButtonClick(object sender, EventArgs e)
		{
			/// <summary>
			/// //////////////////////////////////////////////////////////////////////////////////////
			/// </summary>
		}
		
		void extractPlusInfo(string[] vrstice)
		{
			bool View = false;
			bool Ask = false;
			bool Abstract = false;
			bool Integrity = false;
			//int index = 0;
			//vrstice[vrstice.Length-1] = "+++\r\n";
			List<string> mojeVrstice = new List<string>();
			foreach (string vrstica in vrstice)
			{
				if(View)
				{
					if(vrstica.ToLower().StartsWith("+") == false)
					{
						string temps = vrstica;
						temps = temps.Trim();
						string tempsLang = temps;
						string mojJezik = "";
						string[] tempsLangArray = tempsLang.Split((": ").ToCharArray());
						string[] tempsa = temps.Split((": ").ToCharArray());
						string pogled = "";
						string velikost = "";
						ListViewItem item;
						foreach(string kos in tempsa)
						{
							if(kos.Contains("/"))
							{
								pogled=kos.Trim();
								//viewList.Items.Add(kos.Trim());
								//plusViews.Add(kos.Trim());
							}
							if(kos.Contains("<"))
							{
								velikost = kos.Trim();
							}
							if(kos.Contains("_"))
							{
								mojJezik = mojJezik + " " + kos.Trim();
							}
						}
						if(pogled != "")
						{
							item = listView.Items.Add(pogled.Trim());
							//item.SubItems.Add("test2");
							plusViews.Add(pogled.Trim());
							pogled = "";
							
							if(mojJezik.Contains("_"))
							{
								plusLanguages.Add(mojJezik.Trim());
								item.SubItems.Add(mojJezik.Trim());
								mojJezik="";
							}
							else
							{
								plusLanguages.Add("na");
								item.SubItems.Add("n/a");
								mojJezik="";
							}
							if(velikost != "")
							{
								item.SubItems.Add(velikost);
								plusFileSizes.Add(velikost);
								velikost = "";
							}
							else
							{
								item.SubItems.Add("n/a");
								plusFileSizes.Add("na");
							}
						}
//						if(temps.Contains("<"))
//						{
//							temps = temps.Substring(0,temps.IndexOf("<"));
//						}
//						if(temps.Contains(" "))
//						{
//							temps = temps.Substring(0,temps.IndexOf(" "));
//						}
//						if(temps.Contains(":"))
//						{
//							temps = temps.Substring(0,temps.IndexOf(":"));
//						}
//						if(temps.Trim() != string.Empty)
//						{
//							viewList.Items.Add(temps.Trim());
//							plusViews.Add(temps.Trim());
//							langBox.Text = mojJezik;
//						}
					}
					else View=false;
				}
				if(Ask)
				{
					if(vrstica.ToLower().StartsWith("+") == false)
					{
						plusAsk.Add(vrstica);
					}
					else Ask=false;
				}
				if(Abstract)
				{
					if(vrstica.ToLower().StartsWith("+") == false)
					{
						abstractBox.Text = abstractBox.Text + vrstica.TrimStart() + crlf;
						plusAbstract = plusAbstract + vrstica;
					}
					else Abstract=false;
				}
				if(Integrity)
				{
					if(vrstica.ToLower().StartsWith("+") == false)
					{
						md5Box.Text = md5Box.Text + vrstica;
						plusIntegrity = plusIntegrity + vrstica;
					}
					else Integrity=false;
				}
				if(vrstica.ToLower().StartsWith("+view"))
				{
					View = true;
					//break;
				}
				if(vrstica.ToLower().StartsWith("+ask"))
				{
					Ask = true;
					//break;
				}
				if(vrstica.ToLower().StartsWith("+abstract"))
				{
					Abstract = true;
					//break;
				}
				if(vrstica.ToLower().StartsWith("+integrity"))
				{
					Integrity = true;
					//break;
				}
				if(vrstica.ToLower().StartsWith(" admin:"))
				{
					adminBox.Text = vrstica.Replace("Admin:", string.Empty).Trim();
					plusAdmin = vrstica.Trim();
				}
				if(vrstica.ToLower().StartsWith(" mod-date:"))
				{
					modBox.Text = vrstica.Trim();
					plusModified = vrstica.Trim();
				}
			}
		}
		
		private void getPlusInfoNov2(int currentIndex)
		{
			string myAbstract = "";
			if(ABSTRACTList.Count > 0)
			{
				for(int index = 0; index < ABSTRACTList.Count; index++)
				{
					if(ABSTRACTList[index].Substring(0,ABSTRACTList[index].IndexOf("\t")) == currentIndex.ToString())
					{
						myAbstract=ABSTRACTList[index].Substring(ABSTRACTList[index].IndexOf("\t")).TrimStart();
						break;
					}
				}
			}

			string myAdmin = "";
			if(ADMINList.Count > 0)
			{
				for(int index = 0; index < ADMINList.Count; index++)
				{
					//		MessageBox.Show(index.ToString()+"/"+currentIndex.ToString());
					if(ADMINList[index].Substring(0,ADMINList[index].IndexOf("\t")) == currentIndex.ToString())
					{
						myAdmin=ADMINList[index].Substring(ADMINList[index].IndexOf("\t")).TrimStart();
						break;
					}
				}
			}

			string myView = "";
			if(VIEWList.Count > 0)
			{
				for(int index = 0; index < VIEWList.Count; index++)
				{
					if(VIEWList[index].Substring(0,VIEWList[index].IndexOf("\t")) == currentIndex.ToString())
					{
						//	MessageBox.Show(index.ToString()+"/"+currentIndex.ToString());

						myView=VIEWList[index].Substring(VIEWList[index].IndexOf("\t")).TrimStart();
						break;
					}
				}
			}
			
			string myAsk = "";
			if(ASKList.Count > 0)
			{
				for(int index = 0; index < ASKList.Count; index++)
				{
					if(ASKList[index].Substring(0,ASKList[index].IndexOf("\t")) == currentIndex.ToString())
					{
						//	MessageBox.Show(index.ToString()+"/"+currentIndex.ToString());

						myAsk=ASKList[index].Substring(ASKList[index].IndexOf("\t")).TrimStart();
						break;
					}
				}
			}
			
			string myIntegrity = "";
			if(INTEGRITYList.Count > 0)
			{
				for(int index = 0; index < INTEGRITYList.Count; index++)
				{
					if(INTEGRITYList[index].Substring(0,INTEGRITYList[index].IndexOf("\t")) == currentIndex.ToString())
					{
						//	MessageBox.Show(index.ToString()+"/"+currentIndex.ToString());

						myIntegrity=INTEGRITYList[index].Substring(INTEGRITYList[index].IndexOf("\t")).TrimStart();
						break;
					}
				}
			}
			
//			string myLanguage = "";
//			if(LANGUAGEList.Count > 0)
//			{
//				for(int index = 0; index < LANGUAGEList.Count; index++)
//				{
//					if(LANGUAGEList[index].Substring(0,LANGUAGEList[index].IndexOf("\t")) == currentIndex.ToString())
//					{
//						//	MessageBox.Show(index.ToString()+"/"+currentIndex.ToString());
//
//						myLanguage=LANGUAGEList[index].Substring(LANGUAGEList[index].IndexOf("\t")).TrimStart();
//						break;
//					}
//				}
//			}
			
			//MessageBox.Show(myAbstract+myAdmin+myView);
			string test = "";
			if(myView != string.Empty)
			{
				test = "+VIEW:"+crlf+" "+myView;
			}
			if(myAdmin != string.Empty)
			{
				test = test+"+ADMIN:"+crlf+" "+myAdmin;
			}
			if(myAbstract != string.Empty)
			{
				test = test+"+ABSTRACT:"+crlf+" "+myAbstract;
			}
			if(myIntegrity != string.Empty)
			{
				test = test+"+INTEGRITY:"+crlf+" "+myIntegrity;
			}
			if(myAsk != string.Empty)
			{
				test = test+"+ASK:"+crlf+" "+myAsk;
			}
			
			//MessageBox.Show(test);
			
			string[] imenik = test.Split(crlf.ToCharArray());
			
			extractPlusInfo(imenik);
		}
		
		private bool getPlusInfoNov(string selector, string address, string port)
		{
			List<string> imenik = new List<string>();
			try
			{
				TcpClient client = new TcpClient (address, Convert.ToInt32(port));
				NetworkStream n = client.GetStream();

				SendCommand2 (n, selector+"\t!");
				
				if (n.DataAvailable == false) Thread.Sleep(waitTimeout);
				int i = 0;
				while(imenik.Count == 0)		//
				{								// večkratna ponovitev če večkrat ne dobimo nič...
					i++;
					while (n.DataAvailable)
					{
						string line = ReadLine2 (n);		// e.g.  "1Streznik seanm.ca              seanm.ca        70"
						if (line == ".")
						{
							n.Close();
							break;				// end of server output. we ignore anything past "." alone on the line
						}
						imenik.Add(line);						// add line to list of lines
						if (n.DataAvailable == false) Thread.Sleep(waitTimeout);
					}
					if((i == 5) || (imenik.Count != 0))					// poskusimo petkrat
					{							// to je za to, da nimamo večkratnik ponovitev
						break;					//
					}							//
					Thread.Sleep(waitTimeout);		//
				}
			}
			catch(Exception)
			{
				
			}
			if(imenik.Count > 0)
			{
				extractPlusInfo(imenik.ToArray());
				return true;
			}
			else
			{
				return false;
			}
		}

		private void plusClean()
		{
			modBox.Text = "";
			adminBox.Text = "";
			abstractBox.Text = "";
			md5Box.Text = "";
			plusAbstract = "";
			plusModified = "";
			plusAdmin = "";
			plusViews.Clear();
			plusAsk.Clear();
			plusIntegrity = "";
			listView.Items.Clear();
			plusLanguages.Clear();
			plusFileSizes.Clear();
		}
		
		#region not_used
//		void ViewListDoubleClick(object sender, EventArgs e)
//		{
//			try
//			{
//				// očistimo mime tip
//				string temps = viewList.SelectedItem.ToString().ToLower();
//				//MessageBox.Show(temps);
//				if(temps.Contains("<"))
//				{
//					temps = temps.Substring(0,temps.IndexOf("<"));
//				}
//
//				if(temps.Contains(" "))
//				{
//					temps = temps.Substring(0,temps.IndexOf(" "));
//				}
//				if(temps.Contains(":"))
//				{
//					temps = temps.Substring(0,temps.IndexOf(":"));
//				}
//				//MessageBox.Show(viewList.SelectedItem.ToString().ToLower());
//				if (temps == ("application/gopher-menu") ||
//				    temps == ("application/gopher+-menu") ||
//				    temps == ("directory+/recursive") ||
//				    temps == ("directory/recursive"))
//				{
//					//imenik
//
//					selectorBox.Text = selectList[gopherMenu.SelectedIndex];
//					serverBox.Text = addressList[gopherMenu.SelectedIndex];
//					portBox.Text = portList[gopherMenu.SelectedIndex];
//					DodajZgodovino(descList[gopherMenu.SelectedIndex], selectList[gopherMenu.SelectedIndex], addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex]);
//					DobiImenik(selectList[gopherMenu.SelectedIndex]+"\t+"+temps, addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], iTimeout);
//					plusClean();
//				}
//				else if (temps == ("text/plain"))
//				{
//					//tekstovna datoteka
//					TekstovnoOkno tekstOkno = new TekstovnoOkno(selectList[gopherMenu.SelectedIndex]+"\t+"+temps, addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], iTimeout);
//					tekstOkno.ShowInTaskbar = false;
//					tekstOkno.ShowDialog();
//				}
//				else if (infoList[gopherMenu.SelectedIndex] == "7")
//				{
//					//iskanje po strežniku
//					iskanjePoStrezniku search = new iskanjePoStrezniku();
//					if (search.ShowDialog() == DialogResult.OK)
//					{
//						DodajZgodovino(descList[gopherMenu.SelectedIndex]+" ("+search.iskanje+")", selectList[gopherMenu.SelectedIndex]+"\t"+search.iskanje, addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex]);
//						DobiImenik(selectList[gopherMenu.SelectedIndex]+"\t"+search.iskanje, addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], iTimeout*3);
//					}
//				}
//				else if (infoList[gopherMenu.SelectedIndex] == "i")
//				{
//					//ne naredimo nič - informacije		+
//				}
//				else if (infoList[gopherMenu.SelectedIndex] == "3")
//				{
//					//ne naredimo nič - napaka
//				}
//				else if (infoList[gopherMenu.SelectedIndex] == "8")
//				{
//					//telnet
//					System.Diagnostics.Process.Start("telnet.exe", addressList[gopherMenu.SelectedIndex]+" "+portList[gopherMenu.SelectedIndex]);
//				}
//				else if (infoList[gopherMenu.SelectedIndex] == "2")
//				{
//					//Telefonski imenik
//					ImenikOkno imenik = new ImenikOkno(selectList[gopherMenu.SelectedIndex], addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], iTimeout);
//					imenik.Show();
//				}
//				else if (temps == ("text/html"))
//				{
//					//Spletna stran
//					WebViewer webview = new WebViewer(selectList[gopherMenu.SelectedIndex]+"\t+"+temps, addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], iTimeout, downloadsFolder);
//					webview.Show();
//				}
//				else
//				{
//					DolPotegniPredmet(selectList[gopherMenu.SelectedIndex], addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], "\t+"+temps, md5Box.Text);
//				}
//			}
//			catch (Exception ex)
//			{
//				MessageBox.Show("Before clicking the menu, you need to get it from the server\r\n\r\n"+ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//			}
//		}
		#endregion
		
		void FormatPreferencesToolStripMenuItemClick(object sender, EventArgs e)
		{
			FormatPref FP = new FormatPref(settingsDir);
			if(FP.ShowDialog() == DialogResult.OK)
			{
				ReloadSettings(true);
			}
		}
		
		void MainFormFormClosing(object sender, FormClosingEventArgs e)
		{
			DataSet ds = new DataSet();
			//possible problems due to accented characters in utf file names ... problemi spodaj zaradi utf imen datotek šumniki...
			ds.ReadXml(settingsFile);
			if(plusUse.CheckState == CheckState.Checked)
			{
				ds.Tables[0].Rows[0]["plusOn"] = "on";
			}
			else
			{
				ds.Tables[0].Rows[0]["plusOn"] = "off";
			}
			if(plusRefresh.CheckState == CheckState.Checked)
			{
				ds.Tables[0].Rows[0]["plusRefreshOn"] = "on";
			}
			else
			{
				ds.Tables[0].Rows[0]["plusRefreshOn"] = "off";
			}
			ds.WriteXml(settingsFile, XmlWriteMode.WriteSchema);
		}
		
		void AdminBoxLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
			psi.UseShellExecute = true;
			psi.FileName = "mailto:" + adminBox.Text;
			System.Diagnostics.Process.Start(psi);
		}
		
		void LanguagePreferencesToolStripMenuItemClick(object sender, EventArgs e)
		{
			LanguagePreferences LP = new LanguagePreferences(settingsDir);
			if(LP.ShowDialog() == DialogResult.OK)
			{
				ReloadSettings(true);
			}
		}
		
		void RichTextBoxLinkClicked(object sender, LinkClickedEventArgs e)
		{
			doUrl(e.LinkText, sender, e);
			//MessageBox.Show(e.LinkText);
		}
		
		void goForSelector(string selector)
		{
			if(selector.Contains("\t"))
			{
				string[] delSelektorja = selector.Split(("\t").ToCharArray());
				if(delSelektorja.Length == 5)
				{
					handleGopherRequest(delSelektorja[4],	//plus
					                    (delSelektorja[0][0]).ToString(), //info
					                    delSelektorja[1],	//selector
					                    delSelektorja[2],	//address
					                    delSelektorja[3],	//port
					                    delSelektorja[0].Substring(1));//deskriptor
				}
				else if(delSelektorja.Length == 4)
				{
					handleGopherRequest(string.Empty,	//plus
					                    (delSelektorja[0][0]).ToString(), //info
					                    delSelektorja[1],	//selector
					                    delSelektorja[2],	//address
					                    delSelektorja[3],	//port
					                    delSelektorja[0].Substring(1));//deskriptor
				}
				else
				{
					MessageBox.Show("Error in selector", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
		
		void RichTextBoxMouseClick(object sender, MouseEventArgs e)
		{
			int i = 0;
			string mojlink = "";
			foreach(string link in rtfLinks)
			{
				string[] deli = link.TrimStart().Split((" ").ToCharArray());
				int vrstica = Convert.ToInt32(deli[1]);
				int start = richTextBox.GetFirstCharIndexFromLine(vrstica)+Convert.ToInt32(deli[2]);
				int end = richTextBox.GetFirstCharIndexFromLine(Convert.ToInt32(deli[3]))+Convert.ToInt32(deli[4]);
				int length = end-start;
				//MessageBox.Show(rtfSelectors.Count.ToString());
				if((richTextBox.GetCharIndexFromPosition(new Point(e.X, e.Y)) >= start) &&
				   (richTextBox.GetCharIndexFromPosition(new Point(e.X, e.Y)) <= end))
				{
					//MessageBox.Show("LINK"+i.ToString()+"  "+rtfSelectors[i]);
					mojlink = rtfSelectors[i];
					i=0;
					break;
				}
				i++;
			}
			if(mojlink != "")
			{
				goForSelector(mojlink);
			}
		}
		
		void ListViewDoubleClick(object sender, EventArgs e)
		{
			try
			{
				// cleanup mime type
				string temps = listView.SelectedItems[0].Text.ToLower();
				//MessageBox.Show(temps);
				if(temps.Contains("<"))
				{
					temps = temps.Substring(0,temps.IndexOf("<"));
				}

				if(temps.Contains(" "))
				{
					temps = temps.Substring(0,temps.IndexOf(" "));
				}
				if(temps.Contains(":"))
				{
					temps = temps.Substring(0,temps.IndexOf(":"));
				}
				//MessageBox.Show(viewList.SelectedItem.ToString().ToLower());
				if (temps == ("application/gopher-menu") ||
				    temps == ("application/gopher+-menu") ||
				    temps == ("directory+/recursive") ||
				    temps == ("directory/recursive"))
				{
					//directory					
					selectorBox.Text = selectList[gopherMenu.SelectedIndex];
					serverBox.Text = addressList[gopherMenu.SelectedIndex];
					portBox.Text = portList[gopherMenu.SelectedIndex];
					DodajZgodovino(descList[gopherMenu.SelectedIndex], selectList[gopherMenu.SelectedIndex]+"\t+"+temps, addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex]);
					getDirectory(selectList[gopherMenu.SelectedIndex]+"\t+"+temps, addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex]/*, iTimeout*/);
					plusClean();
				}
				else if (temps == ("text/plain"))
				{
					//text file
					TekstovnoOkno tekstOkno = new TekstovnoOkno(selectList[gopherMenu.SelectedIndex]+"\t+"+temps, addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], waitTimeout);
					tekstOkno.ShowInTaskbar = false;
					tekstOkno.ShowDialog();
				}
				else if (infoList[gopherMenu.SelectedIndex] == "7")
				{
					//server search
					iskanjePoStrezniku search = new iskanjePoStrezniku();
					if (search.ShowDialog() == DialogResult.OK)
					{
						DodajZgodovino(descList[gopherMenu.SelectedIndex]+" ("+search.iskanje+")", selectList[gopherMenu.SelectedIndex]+"\t"+search.iskanje, addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex]);
						getDirectory(selectList[gopherMenu.SelectedIndex]+"\t"+search.iskanje, addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex]/*, iTimeout*3*/);
					}
				}
				else if (infoList[gopherMenu.SelectedIndex] == "i")
				{
					//do nothing - info		+
				}
				else if (infoList[gopherMenu.SelectedIndex] == "3")
				{
					//do nothing (error)
				}
				else if (infoList[gopherMenu.SelectedIndex] == "8")
				{
					//telnet
					System.Diagnostics.Process.Start("telnet.exe", addressList[gopherMenu.SelectedIndex]+" "+portList[gopherMenu.SelectedIndex]);
				}
				else if (infoList[gopherMenu.SelectedIndex] == "2")
				{
					//phone book
					ImenikOkno imenik = new ImenikOkno(selectList[gopherMenu.SelectedIndex], addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], waitTimeout);
					imenik.Show();
				}
				else if (temps == ("text/html"))
				{
					//web site
					WebViewer webview = new WebViewer(selectList[gopherMenu.SelectedIndex]+"\t+"+temps, addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], waitTimeout, downloadsFolder);
					webview.Show();
				}
				else
				{
					if(listView.SelectedIndices[0] == 0)
					{
						DolPotegniPredmet(selectList[gopherMenu.SelectedIndex], addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], "\t+"+temps, md5Box.Text);
					}
					else
					{
						DolPotegniPredmet(selectList[gopherMenu.SelectedIndex], addressList[gopherMenu.SelectedIndex], portList[gopherMenu.SelectedIndex], "\t+"+temps, string.Empty);
					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show("Before clicking the menu, you need to get it from the server"+Environment.NewLine+Environment.NewLine+ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		
		void TestToolStripMenuItemClick(object sender, EventArgs e)
		{
			if(listView.SelectedItems.Count == 1)
			{
				StreamReader SR;
				StreamWriter SW;
				
				try
				{
					SR = new StreamReader(settingsDir+"format.dat");
					List<string> prefList = new List<string>();
					while(SR.EndOfStream == false)
					{
						prefList.Add(SR.ReadLine());
					}
					SR.Close();
					
					prefList.Add(listView.SelectedItems[0].Text.ToLower());
					
					SW = new StreamWriter(settingsDir+"format.dat");
					for(int i = 0; i < prefList.Count; i++)
					{
						SW.WriteLine(prefList[i].ToLower().Trim());
					}
					SW.Flush();
					SW.Close();
					ReloadSettings(true);
				}
				catch(Exception ex)
				{
					MessageBox.Show("Error reading/writting file"+Environment.NewLine+Environment.NewLine+ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
		
		void PlusRefreshClick(object sender, EventArgs e)
		{
			if(plusRefresh.CheckState != CheckState.Checked)
			{
				splitContainer.Panel2Collapsed = true;
			}
		}
		
		void GoToURLToolStripMenuItemClick(object sender, EventArgs e)
		{
			urlForm UF = new urlForm();
			if(UF.ShowDialog() == DialogResult.OK)
			{
				//MessageBox.Show(UF.url);
				//doUrl(Uri.UnescapeDataString(UF.url), sender, e);
				doUrl(UF.url, sender, e);
			}
		}
		
		void ClearHistoryToolStripMenuItem1Click(object sender, EventArgs e)
		{
			CleanHistory();
			indexHist.Clear();
			descHist.Clear();
			selectHist.Clear();
			addressHist.Clear();
			portHist.Clear();
		}
	}
	
	class DownloadThread
	{
		string mojSelektor;
		string mojStreznik;
		string mojaVrata;
		string mojIntegrity;
		string settingsdir;

		public DownloadThread(string selektor, string streznik, string vrata, string integrity, string settingDir)
		{
			mojSelektor = selektor;
			mojStreznik = streznik;
			mojaVrata = vrata;
			mojIntegrity = integrity;
			settingsdir = settingDir;
		}

		public void ThreadFunction()
		{
			Dolpoteg DownloadWindow = new Dolpoteg(mojSelektor, mojStreznik, mojaVrata, mojIntegrity, settingsdir);
			DownloadWindow.ShowInTaskbar = false;
			DownloadWindow.ShowDialog();
		}
	}
}
